from __future__ import print_function
from lmdb_aws import session, Folder, Keyword, TaskKeyword
import datetime
import PyQt4.QtGui as QtGui
import re
#import lmglobals as g

def responses(source, d):

    print("source={}".format(source))
    for z in d:
        print("{}: {}".format(z,d[z]))

    task = d.get('task')
    session = d.get('session')    

    if source=='newtask':
        if task.context.title!='test':
            task.remind = 1
            task.duedate=task.duetime = datetime.datetime.now() + datetime.timedelta(days=1)
            session.commit()

            task.tag = 'to do'
            session.commit()
    
            keyword = session.query(Keyword).filter_by(name='to do').first()
            if keyword is None:
                keyword = Keyword('to do')
                session.add(keyword)
            tk = TaskKeyword(task,keyword)
            session.add(tk)

            session.commit()

    if source=='incrementpriority':
        priority = d.get('priority')
        if priority == -1:
            QtGui.QMessageBox.question(None,  'Alert', "Are you sure you want a priority of -1?")

    if source=='save_title':
        title = d.get('title')
        mapping = {'mjw':'marty','marty':'marty', 'schedule':'calendar','meeting':'calendar', 'calendar':'calendar','phone':'phone','call':'phone','followup':'followup','follow-up':'followup', 'follow up':'followup'}

        for word in mapping.keys():

            if re.search("\\b{0}\\b".format(word), title, re.IGNORECASE):  #r'\bcall\b' #re.search(r'\bword\b', title, re.IGNORECASE)
                folder = session.query(Folder).filter_by(title=mapping[word]).first()

                if not folder:
                    print("couldn't find a folder for  {}".format(word))
                    next

                task.folder = folder
                session.commit()
                print("task was assigned folder: {}".format(task.folder.title))

                break
